package org.example.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;

public class MyWebSocketClient extends WebSocketClient {
    private CountDownLatch handshakeSuccess;
    private CountDownLatch connectClose;
    public SseEmitter sseEmitter;

    public MyWebSocketClient(URI serverUri, Draft protocolDraft, CountDownLatch handshakeSuccess, CountDownLatch connectClose,SseEmitter sseEmitter) {
        super(serverUri, protocolDraft);
        this.handshakeSuccess = handshakeSuccess;
        this.connectClose = connectClose;
        this.sseEmitter = sseEmitter;
    }

    @Override
    public void onOpen(ServerHandshake handshake) {
        System.out.println("连接建立成功！");
    }

    @Override
    public void onMessage(String msg) {
        JSONObject msgObj = JSONObject.parseObject(msg);
        String action = msgObj.getString("action");
        if (Objects.equals("started", action)) {
            // 握手成功
            System.out.println("\t握手成功！sid: " + msgObj.getString("sid"));
            handshakeSuccess.countDown();
        } else if (Objects.equals("result", action)) {
            // 转写结果
            try {
                System.out.println("\t转写结果：" + getContent(msgObj.getString("data")));
                // 如果sseemitter还没有关闭 发送数据
                sseEmitter.send(getContent(msgObj.getString("data")));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void onError(Exception e) {
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        System.out.println("\t链接关闭");
        connectClose.countDown();
    }

    @Override
    public void onMessage(ByteBuffer bytes) {
        try {
            System.out.println("\t服务端返回：" + new String(bytes.array(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    // 把转写结果解析为句子
    private static String getContent(String message) {
        StringBuffer resultBuilder = new StringBuffer();
        try {
            JSONObject messageObj = JSON.parseObject(message);
            JSONObject cn = messageObj.getJSONObject("cn");
            JSONObject st = cn.getJSONObject("st");
            JSONArray rtArr = st.getJSONArray("rt");
            for (int i = 0; i < rtArr.size(); i++) {
                JSONObject rtArrObj = rtArr.getJSONObject(i);
                JSONArray wsArr = rtArrObj.getJSONArray("ws");
                for (int j = 0; j < wsArr.size(); j++) {
                    JSONObject wsArrObj = wsArr.getJSONObject(j);
                    JSONArray cwArr = wsArrObj.getJSONArray("cw");
                    for (int k = 0; k < cwArr.size(); k++) {
                        JSONObject cwArrObj = cwArr.getJSONObject(k);
                        String wStr = cwArrObj.getString("w");
                        resultBuilder.append(wStr);
                    }
                }
            }
        } catch (Exception e) {
            return message;
        }

        return resultBuilder.toString();
    }
}
